package com.corecloud.security.oauth;

import com.corecloud.entity.SysAppEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.util.StringUtils;

import java.util.*;

public class ClientDetailsImp implements ClientDetails {

	
	private static final long serialVersionUID = 1L;
	
	private SysAppEntity app;
	
	public ClientDetailsImp(SysAppEntity app) {
		this.app = app;
	}

	@Override
	public Set<String> getResourceIds() {
		String resourceIds = app.getResourceIdMul();
		if (!StringUtils.isEmpty(resourceIds)) {
			return stringToSet(resourceIds);
		} else {

			return new HashSet<String>(){{add("coreservice");}};
		}
	}

	@Override
	public boolean isSecretRequired() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isScoped() {
		return true;
	}

	@Override
	public Set<String> getScope() {
		String scopes = app.getScopeMul();
		if (!StringUtils.isEmpty(scopes)) {
			return stringToSet(scopes);
		} else {
			return new HashSet<String>(){{add("basic");}};
		}
		
	}
	
	private Set<String> stringToSet(String str){
		if (!StringUtils.isEmpty(str)) {
			String[] arStr = str.split(",");
			Set<String> setStr = new HashSet<String>();
			for (String s : arStr) {
				setStr.add(s);
			}
			return setStr;
		} else {
			return new HashSet<String>();
		}
	}

	@Override
	public Set<String> getAuthorizedGrantTypes() {
		// TODO Auto-generated method stub
		return stringToSet(app.getGrantTypeMul());
	}

	@Override
	public Set<String> getRegisteredRedirectUri() {
		// TODO Auto-generated method stub
		return stringToSet(app.getRedirectUriMul());
	}

	@Override
	public Collection<GrantedAuthority> getAuthorities() {
		// TODO Auto-generated method stub
		//BaseClientDetails
		return Collections.emptySet();
	}

	@Override
	public boolean isAutoApprove(String scope) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public Map<String, Object> getAdditionalInformation() {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public Integer getAccessTokenValiditySeconds() {
		Object o = app.getAccessTokenValiditySeconds();
		if (!StringUtils.isEmpty(o)) {
			int i = Integer.parseInt(o.toString());
			return i;
		} else {
			return 2*60*60;
		}
		
	}
	
	@Override
	public Integer getRefreshTokenValiditySeconds() {
		Object o = app.getRefreshTokenValiditySeconds();
		if (!StringUtils.isEmpty(o)) {
			int i = Integer.parseInt(o.toString());
			return i;
		} else {
			return 24*60*60;
		}
	}

	@Override
	public String getClientId()
	{
		// TODO Auto-generated method stub
		return app.getClientId();
	}

	@Override
	public String getClientSecret() {
		// TODO Auto-generated method stub
		return app.getClientSecret();
	}

}
